package com.zrb.applib.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.graphics.Bitmap;
import android.util.Log;

public class FileUtil
{
	public static String filePath = android.os.Environment.getExternalStorageDirectory() + "/ZRBDownLoad";
    public final static String  tagName="ZRB_tag";
    public final static String  NewTypeName="ZRB_tag";
    
	public static String getFileName(String str)
	{
		// 去除url中的符号作为文件名返回
		str = str.replaceAll("(?i)[^a-zA-Z0-9\u4E00-\u9FA5]", "");
		System.out.println("filename = " + str);
		return str + ".png";
	}

	 
	/** 
	* 移动文件 
	* @param srcFileName 	源文件完整路径
	* @param destDirName 	目的目录完整路径
	* @return 文件移动成功返回true，否则返回false 
	*/  
	public static boolean moveFile(String srcFileName, String destDirName) {
		
		File srcFile = new File(srcFileName);
		if(!srcFile.exists() || !srcFile.isFile()) 
		    return false;
		
		File destDir = new File(destDirName);
		if (!destDir.exists())
			destDir.mkdirs();
		return srcFile.renameTo(new File(destDirName + File.separator + srcFile.getName()));
	}
	
   public static boolean isBitmapExists(String filedir,String filename) {
	        File dir =new File(filePath+filedir);
	         if(!dir.exists()){
	             dir.mkdirs();
	            }
	                //context.getExternalFilesDir(null);
	        File file = new File(dir, filename);

	        return file.exists();
	}
	
	public static void writeFileSdcard(String fileName, String message) {

		try {
 			File file = new File(filePath);
			if (!file.exists()) {
				file.mkdirs();
			}

			FileOutputStream fout = new FileOutputStream(filePath + "/" + fileName);
			byte[] bytes = message.getBytes();
			fout.write(bytes);
			fout.close();
		}
 		catch (Exception e) {
 			e.printStackTrace();
 			System.out.println("writeToSD fail");
 		}

	}
	
	public static void writeFileSdcardhasDir(String dir,String fileName, String message) {

		try {
 			File file = new File(filePath+dir);
			if (!file.exists()) {
				file.mkdirs();
			}

			FileOutputStream fout = new FileOutputStream(filePath +dir+ "/" + fileName);
/*			if (!file.exists()) {
				file.createNewFile();
			}*/
			
			byte[] bytes = message.getBytes();
			fout.write(bytes);
			fout.close();
		}
 		catch (Exception e) {
 			e.printStackTrace();
 			System.out.println("writeToSD fail");
 		}

	}
	
	public static void writeSDcard(String fileName, InputStream inputStream)
	{
		try
		{
			File file = new File(filePath);
			if (!file.exists())
			{
				file.mkdirs();
			}

			FileOutputStream fileOutputStream = new FileOutputStream(filePath + "/" + fileName);
			byte[] buffer = new byte[512];
			int count = 0;
			while ((count = inputStream.read(buffer)) > 0)
			{
				fileOutputStream.write(buffer, 0, count);
			}
			fileOutputStream.flush();
			fileOutputStream.close();
			inputStream.close();
			System.out.println("writeToSD success");
		} catch (IOException e)
		{
			e.printStackTrace();
			System.out.println("writeToSD fail");
		}
	}

	 /**
     * 保存图片到制定路径
     * 
     * @param filepath
     * @param bitmap
     */
    public static void saveBitmap(String dir,String filename, Bitmap bitmap) {
 
        if (bitmap == null) {
            return;
        }
     
        try {
            
            File file = new File(filePath+dir,filename);
            FileOutputStream outputstream = new FileOutputStream(file);
            if((filename.indexOf("png") != -1)||(filename.indexOf("PNG") != -1))  
            {  
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputstream);
            }  else{
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputstream);
            }
            
            outputstream.flush();
            outputstream.close();
            
        } catch (FileNotFoundException e) {
            Log.i("TAG", e.getMessage());
        } catch (IOException e) {
            Log.i("TAG", e.getMessage());
        } 
    }
	
	public static boolean writeSDcard(String fileName, Bitmap bmp)
	{
		try
		{
			File file = new File(filePath);

			if (!file.exists())
			{
				file.mkdirs();
			}
			File imgFile = new File(filePath + "/" + getFileName(fileName));
			if (imgFile.exists())
			{
				return true;
			}
			InputStream is = bitmap2InputStream(bmp);
			FileOutputStream fileOutputStream = new FileOutputStream(imgFile);
			byte[] buffer = new byte[512];
			int count = 0;
			while ((count = is.read(buffer)) > 0)
			{
				fileOutputStream.write(buffer, 0, count);
			}
			fileOutputStream.flush();
			fileOutputStream.close();
			is.close();
			System.out.println("writeToSD success");
		} catch (IOException e)
		{
			e.printStackTrace();
			System.out.println("writeToSD fail");
			return false;
		}
		return true;
	}

	// Bitmap转换成byte[]
	public static byte[] bitmap2Bytes(Bitmap bm)
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}

	// 将Bitmap转换成InputStream
	public static InputStream bitmap2InputStream(Bitmap bm)
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		// Write a compressed version of the bitmap to the specified
		// outputstream.
		bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
		InputStream is = new ByteArrayInputStream(baos.toByteArray());
		return is;
	}
	
	public static byte[] getBytesFromFile(File f){
        if (f == null) {
            return null;
        }
        try {
            FileInputStream stream = new FileInputStream(f);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1)
                out.write(b, 0, n);
            stream.close();
            out.close();
            return out.toByteArray();
        } 
        catch (IOException e) 
        {
        }
        return null;
    }
}
